package com.tuju.jetpackfirstdemo.ui.rv_loadmore

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import com.tuju.jetpackfirstdemo.R
import com.tuju.jetpackfirstdemo.adapter.DemoRvAdapter
import com.tuju.jetpackfirstdemo.base.baseadapter.LoadMoreAdapter
import com.tuju.jetpackfirstdemo.utils.showToast
import com.tuju.jetpackfirstdemo.widget.MyItemDecoration
import kotlinx.android.synthetic.main.activity_load_more.*
import java.util.*

class LoadMoreActivity : AppCompatActivity() {

    lateinit var adapter: LoadMoreAdapter<String>

    private var testIsHasData = true

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_load_more)
        rv_demo.layoutManager = LinearLayoutManager(this@LoadMoreActivity)
        adapter = LoadMoreAdapter()
        adapter.setLoadMoreEnable(true)
        adapter.setLoadMoreListener(object : LoadMoreAdapter.LoadMoreListener {
            override fun onLoadMoreLoading() {
                if (testIsHasData) {
                    showToast("加载更多了...")
                    rv_demo.postDelayed({
                        adapter.loadMoreComplete()
                        addData()
                    }, 2000)
                    testIsHasData = false
                } else {
                    rv_demo.postDelayed({
                        adapter.loadMoreComplete()
                        adapter.noMoreLoading()
                    }, 1000)
                    showToast("没有更多数据了...")
                }
            }
        })
        rv_demo.adapter = adapter
        rv_demo.addItemDecoration(MyItemDecoration())
        initData()
    }

    private fun initData() {
        val datas = Arrays.asList("哈哈1", "嘿嘿2", "嘿嘿3", "嘿嘿4", "嘿嘿5", "嘿嘿6", "嘿嘿7", "嘿嘿8", "嘿嘿9", "嘿嘿10", "哈哈11"
                , "哈哈1", "嘿嘿2", "嘿嘿3", "嘿嘿4", "嘿嘿5", "嘿嘿6", "嘿嘿7", "嘿嘿8", "嘿嘿9", "嘿嘿10", "哈哈11")
        adapter.addAll(datas)
        adapter.notifyDataSetChanged()
    }

    private fun addData() {
        val datas = Arrays.asList("新增1", "新增2", "新增3", "新增4", "新增5")
        var position = adapter.itemCount + 1
        adapter.addAll(datas)
        adapter.notifyItemRangeInserted(position, adapter.getData().size)
    }
}
